package com.wasu.netutils;

import static com.wasu.sdk_ott.provider.WasuSdkUriMatcherKt.PATH_WASU_SDK_CONTENT_AUTHORITY;
import static com.wasu.sdk_ott.provider.WasuSdkUriMatcherKt.PATH_WASU_SDK_PLUGIN_AUTHORITY;

import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.util.Log;

import com.wasu.doicommon.util.LogUtils;

import java.util.concurrent.ConcurrentHashMap;

/**
 * <p>------------------------------------------------------
 * <p>Copyright (C) 2020 wasu company, All rights reserved.
 * <p>------------------------------------------------------
 * <p>
 * <p>
 *
 * @author Ant
 * @date on 2020/5/18 14:49.
 */
class BaseDataSource {
    private static final String TAG = "BaseDataSource";
    public static Context context;
    private static final String CONTENT_AUTHORITY = PATH_WASU_SDK_CONTENT_AUTHORITY;
    private static final String WASU_PLUGIN_AUTHORITY = PATH_WASU_SDK_PLUGIN_AUTHORITY;
    /**
     * 新门户使用的都是此URI
     */
    private static final Uri BASE_URI = Uri.parse("content://" + CONTENT_AUTHORITY + "/" + WASU_PLUGIN_AUTHORITY);

    private final ConcurrentHashMap<String, Uri> uriCache = new ConcurrentHashMap<>();

    /**
     * 获取新的内容提供者的Uri
     */
    Uri fetchUri(String uriPath) {
        Uri uri = uriCache.get(uriPath);
        if (uri == null) {
            uri = BASE_URI.buildUpon().appendPath(uriPath).build();
            uriCache.put(uriPath, uri);
        }
        return uri;
    }

    /**
     * 返回业务数据管理系统相关接口结果
     */
    String fetchBusDataManageRes(Uri uri, String[] args) {
        return fetchRes(uri, args, UriPath.BUS_DATA_MANAGE_SYSTEM_RESULT);
    }

    private String fetchRes(Uri uri, String[] args, String resultKey) {
        if (context == null) {
            LogUtils.eTag(TAG, "ctx == null.");
            return "";
        }
        try (Cursor cursor = context.getContentResolver().query(uri, args, null, null, null)) {
            if (cursor == null || !cursor.moveToNext()) {
                Log.e(TAG, "fetchRes: cursor = null or no data.");
                return null;
            }
            int index = cursor.getColumnIndex(resultKey);
            if (index >= 0) {
                final String result = cursor.getString(index);
                Log.d(TAG, "fetchRes: " + result);
                return result;
            }
        }
        return "";
    }

}
